package com.jiulan.hearthearing.ui.login.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.jiulan.hearthearing.R;
import com.jiulan.hearthearing.base.BaseActivity;
import com.jiulan.hearthearing.base.BaseModel;
import com.jiulan.hearthearing.common.MethodUtils;
import com.jiulan.hearthearing.constants.UrlConstants;
import com.jiulan.hearthearing.http.HttpRequest;
import com.jiulan.hearthearing.http.HttpStringCallBack;
import com.jiulan.hearthearing.ui.login.model.LoginModel;
import com.jiulan.hearthearing.utils.SoftKeyboardUtils;
import com.jiulan.hearthearing.utils.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 注册页面
 */
public class RegisterActivity extends BaseActivity implements View.OnClickListener {
    private String mobile = "";
    private String mgsCode = "";
    private String password = "";
    private String password2 = "";
    private boolean isPasswordVisiable = false;
    private boolean isPassword2Visiable = false;

    private static final int CODE_ING = 1;//已发送，倒计时
    private static final int CODE_REPEAT = 2;//重新发送
    private int TIME = 60;// 倒计时60s

    private EditText etMobile;
    private EditText etMsgCode;
    private EditText etPassword;
    private EditText etPassword2;
    private ImageView ivClear;
    private TextView tvGetCode;
    private ImageView ivEye;
    private ImageView ivEye2;
    private TextView tvRegist;
    private TextView tvAgreement;

    public static void actionStart(Context context) {
        Intent intent = new Intent(context, RegisterActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        setAndroidNativeLightStatusBar(true);
    }

    @Override
    protected int setLayoutResourceID() {
        return R.layout.activity_register;
    }

    @Override
    protected void initView() {
        setTitleText("注册");
        etMsgCode = findViewById(R.id.etMsgCode);
        etMobile = findViewById(R.id.etMobile);
        etPassword = findViewById(R.id.etPassword);
        etPassword2 = findViewById(R.id.etPassword2);
        ivClear = findViewById(R.id.ivClear);
        tvGetCode = findViewById(R.id.tvGetCode);
        ivEye = findViewById(R.id.ivEye);
        ivEye2 = findViewById(R.id.ivEye2);
        tvRegist = findViewById(R.id.tvRegist);
        tvAgreement = findViewById(R.id.tvAgreement);
        ivClear.setOnClickListener(this);
        tvGetCode.setOnClickListener(this);
        ivEye.setOnClickListener(this);
        ivEye2.setOnClickListener(this);
        tvRegist.setOnClickListener(this);
        tvAgreement.setOnClickListener(this);
        check();
        etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    mobile = charSequence.toString().trim();
                } catch (Exception e) {
                    mobile = "";
                }
                check();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etMsgCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    mgsCode = charSequence.toString().trim();
                } catch (Exception e) {
                    mgsCode = "";
                }
                check();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    password = charSequence.toString().trim();
                } catch (Exception e) {
                    password = "";
                }
                check();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
        etPassword2.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                try {
                    password2 = charSequence.toString().trim();
                } catch (Exception e) {
                    password2 = "";
                }
                check();
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public int getTitleBarType() {
        return TITLEBAR_DEFAULT;
    }

    private void check() {
        if (StringUtils.isPhoneNumber(mobile) && mgsCode.length() == 6 && StringUtils.isPasswordCorrect(password) && StringUtils.isPasswordCorrect(password2)) {
            tvRegist.setClickable(true);
            tvRegist.setBackgroundResource(R.drawable.login_blue_bg);
        } else {
            tvRegist.setClickable(false);
            tvRegist.setBackgroundResource(R.drawable.login_gray_bg);
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivClear:
                etMobile.setText("");
                break;
            case R.id.tvGetCode://获取验证码
                if (StringUtils.isPhoneNumber(mobile)) {
                    getMobileMsgCode();
                } else {
                    Toast.makeText(getContext(), "请填写正确的手机号码", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.ivEye:
                if (isPasswordVisiable) {//可见时，点击变为不可见
                    etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ivEye.setImageResource(R.mipmap.eye_check);
                    isPasswordVisiable = false;
                } else {//不可见时，点击变为可见
                    etPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ivEye.setImageResource(R.mipmap.eye_close);
                    isPasswordVisiable = true;
                }
                break;
            case R.id.ivEye2:
                if (isPassword2Visiable) {//可见时，点击变为不可见
                    etPassword2.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    ivEye2.setImageResource(R.mipmap.eye_check);
                    isPassword2Visiable = false;
                } else {//不可见时，点击变为可见
                    etPassword2.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    ivEye2.setImageResource(R.mipmap.eye_close);
                    isPassword2Visiable = true;
                }
                break;
            case R.id.tvRegist://点击注册
                SoftKeyboardUtils.hideSoftKeyboard(this);
                register();
                break;
            case R.id.tvAgreement:
                break;
        }
    }

    private void register() {
        Map<String, String> map = new HashMap();
        map.put("account", mobile);
        map.put("captcha", mgsCode);
        map.put("password", password);
        map.put("spread", "0");
        new HttpRequest(getContext()).doPost(UrlConstants.login_register, "", map, LoginModel.class, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {
                if (result instanceof LoginModel) {
                    LoginModel model = (LoginModel) result;
                    Toast.makeText(getContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
                    MethodUtils.loginAfter(RegisterActivity.this, mobile, model.getData().getToken());
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    /**
     * 获取手机验证码
     */
    private void getMobileMsgCode() {
        HashMap hashMap = new HashMap();
        hashMap.put("phone", mobile);
        hashMap.put("type", "register");
        new HttpRequest(getContext()).doPost(UrlConstants.login_verify, "", hashMap, new HttpStringCallBack() {
            @Override
            public void onSuccess(Object result) {

                if (result instanceof BaseModel) {
                    BaseModel model = (BaseModel) result;
                    if (model.getStatus() == 200) {
                        tvGetCode.setClickable(false);
                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                for (int i = 60; i > 0; i--) {
                                    handler.sendEmptyMessage(CODE_ING);
                                    if (i <= 0) {
                                        break;
                                    }
                                    try {
                                        Thread.sleep(1000);
                                    } catch (InterruptedException e) {
                                        e.printStackTrace();
                                    }
                                }
                                handler.sendEmptyMessage(CODE_REPEAT);
                            }
                        }).start();
                    } else {
                        Toast.makeText(getContext(), model.getMsg(), Toast.LENGTH_SHORT).show();
                    }
                }
            }

            @Override
            public void onFailure(int code, String msg) {
            }
        });
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CODE_ING:
                    tvGetCode.setText(--TIME + "后重新获取");
                    break;
                case CODE_REPEAT:
                    tvGetCode.setText("获取验证码");
                    tvGetCode.setClickable(true);
                    TIME = 60;
                    break;
                default:
                    break;
            }
        }
    };
}
